package com.yinhai.asynctask;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.yinhai.httpclient.HttpClientManager;
import com.yinhai.httpclient.HttpClientMethod;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;

/**
 * 注意AsyncTask类的实例只能执行一次execute（），如果需要执行多次excute(),则每次都需要创建一个新对象
 * @author Administrator
 *
 */
public abstract class AsyncTaskForHttp extends AsyncTask<AsyncTaskParam, Integer, Map<String, Object>>{
	protected static int DEFAULT_REQUEST_COUNT = 3;
	/**
	 * 超时后重复请求的次数
	 */
	protected int timeoutRequestCount;
	
	protected Context context;
	
//	protected ProgressDialog dialog;
	
	protected AsyncTaskParam asyncTaskParam;
	/**
	 * 加载完后自动跳转的目标activity
	 */
	protected boolean autoForword;
	
	public AsyncTaskForHttp(Context context){
		this(context, DEFAULT_REQUEST_COUNT, true);
	}
	
	public AsyncTaskForHttp(Context context,boolean autoForword){
		this(context,DEFAULT_REQUEST_COUNT,autoForword);
	}
	
	public AsyncTaskForHttp(Context context,int timeoutRequestCount,boolean autoForword){
		this.context = context;
		this.timeoutRequestCount = timeoutRequestCount;
		this.autoForword = autoForword;
		
	}
	public int getTimeoutRequestCount() {
		return timeoutRequestCount;
	}
	public void setTimeoutRequestCount(int timeoutRequestCount) {
		this.timeoutRequestCount = timeoutRequestCount;
	}
	
	@Override
	protected Map<String, Object> doInBackground(AsyncTaskParam... params) {
		if(params.length < 1){
			Log.e(this.getClass().getName(),"param is error!");
			return null;
		}
		Map<String,Object> resultMap = new HashMap<String, Object>();
		AsyncTaskParam requestParam = params[0];
		this.asyncTaskParam = requestParam;
		
		String content = null;
		if(timeoutRequestCount < 1){
			timeoutRequestCount = 1;
		}
		try{
			HttpClientManager.CreateInstance().initialize();
			for(int i = 0; i < timeoutRequestCount; i ++){
				try {
					
					String url = requestParam.getRemoteURL();
					URLEncoder.encode(url, "utf-8");
					content = HttpClientMethod.PostMethod(url, requestParam.getPostParam());
					resultMap.put(AsyncTaskContext.REQUEST_STATUS, "0");
					break;
				}catch(Exception e){
					//STATUS：请求状态1：失败；0：成功
					resultMap.put(AsyncTaskContext.REQUEST_STATUS, "1");
					e.printStackTrace();
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			//HttpClientManager.GetInstance().destroy();
		}
		resultMap.put(AsyncTaskContext.RESPONSE_CONTENT, content);
		return resultMap;
	}

	@Override
	protected void onPostExecute(Map<String, Object> result) {
		if(result == null){
//			if(dialog != null)dialog.dismiss();
			return;
		}
		if("1".equals(result.get(AsyncTaskContext.REQUEST_STATUS))){
//			if(dialog != null){
//				dialog.setMessage(ConfirmMessageContext.LOADING_FAILURE);
//				dialog.dismiss();
//			}
			
//			AlertDialog.Builder dialog=new AlertDialog.Builder(context);
//        	dialog.setTitle("提示").setIcon(android.R.drawable.ic_dialog_info).setMessage(ConfirmMessageContext.LOADING_FAILURE).setPositiveButton("确定", new DialogInterface.OnClickListener() {
//	        	public void onClick(DialogInterface dialog, int which) {
//	        		dialog.cancel();
//	        	}
//        	}).create().show();
			return;
		}else{
//			if(dialog != null)dialog.dismiss();
		}
		
//		if(this.autoForword){
//			this.startActivity(result);
//		}else{
			this.parse(result);
//		}
	}
	
	
	protected void startActivity(Map<String, Object> result){
		if(this.asyncTaskParam.getIntent() == null){
			Log.e(this.getClass().getName(),"Intent is null!");
		}
		
		this.asyncTaskParam.getIntent().putExtra(AsyncTaskContext.RESPONSE_CONTENT, (String)result.get(AsyncTaskContext.RESPONSE_CONTENT));
		this.context.startActivity(this.asyncTaskParam.getIntent());
	}

	protected abstract void parse(Map<String, Object> result);

}